<template>
	<view class="container">
		<view class="device-info">
			<text>产品ID: {{ product_id }}</text>
			<text>设备名称: {{ device_name }}</text>
			<text>设备状态: {{ device_status }}</text>
		</view>

		<button @click="submitForm1">刷新数据</button>

		<view class="table-container">
			<text class="table-title">物模型数据</text>
			<table class="data-table">
				<thead>
					<tr>
						<th>Identifier</th>
						<th>Name</th>
						<th>Mode</th>
						<th>Value</th>
						<th>Time</th>
					</tr>
				</thead>
				<tbody>
					<tr v-for="item in deviceModelData" :key="item.identifier">
						<td>{{ item.identifier }}</td>
						<td>{{ item.name }}</td>
						<td>{{ item.accessMode }}</td>
						
						<td>{{ item.value }}</td>
						<td>{{ formatTimestamp(item.time) }}</td>
					</tr>
				</tbody>
			</table>
		</view>

		<view class="table-container">
			<text class="table-title">设置设备属性</text>
			<table class="data-table">
				<thead>
					<tr>
						<th>Name</th>
						<th>Input</th>
						<th>Action</th>
					</tr>
				</thead>
				<tbody>
					<tr v-for="item in writableModels" :key="item.identifier">
						<td>{{ item.name }}</td>
						<td>
							<input v-model="item.newValue" placeholder="Enter value" />
						</td>
						<td>
							<button @click="setModelValue(item)">设置</button>
						</td>
					</tr>
				</tbody>
			</table>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				product_id: '',
				device_name: '',
				authorization: '',
				device_status: '',
				lastOnlineTime: '',
				deviceModelData: [],
				writableModels: []
			};
		},

		onLoad() {
			const userInfo = uni.getStorageSync('userInfo');
			if (userInfo) {
				this.product_id = userInfo.product_id;
				this.device_name = userInfo.device_name;
				this.authorization = userInfo.authorization;
				this.device_status = userInfo.device_status;
			} else {
				this.product_id = '未知';
				this.device_name = '未知';
				this.device_status = '未知';
			}

			// 调用数据提取方法
			this.submitForm1();
		},

		methods: {
			formatTimestamp(timestamp) {
			      const date = new Date(timestamp);
			      const year = date.getFullYear();
			      const month = String(date.getMonth() + 1).padStart(2, '0');
			      const day = String(date.getDate()).padStart(2, '0');
			      const hours = String(date.getHours()).padStart(2, '0');
			      const minutes = String(date.getMinutes()).padStart(2, '0');
			      const seconds = String(date.getSeconds()).padStart(2, '0');
			      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			    },
			extractData(res) {
				this.deviceModelData = res.data.data.map(item => ({
					identifier: item.identifier,
					accessMode: item.access_mode,
					name: item.name,
					value: item.value,
					dataType: item.data_type ,// 添加数据类型
					time: item.time,
				}));

				this.writableModels = this.deviceModelData
					.filter(item => item.accessMode === '读写')
					.map(item => ({
						...item,
						newValue: ''
					}));
			},

			submitForm1() {
				uni.request({
					url: 'https://iot-api.heclouds.com/thingmodel/query-device-property',
					method: 'GET',
					header: {
						'Accept': 'application/json, text/plain, */*',
						'authorization': this.authorization
					},
					data: {
						'product_id': this.product_id,
						'device_name': this.device_name
					},
					success: (res) => {
						if (res.statusCode === 200) {
							console.log('请求成功:', res);
							this.extractData(res);
							// 处理设备状态
							const deviceStatus = res.data.data.status;
							if (deviceStatus === 0) {
								this.device_status = '离线';
							} else if (deviceStatus === 1) {
								this.device_status = '在线';
							} else if (deviceStatus === 2) {
								this.device_status = '未激活';
							}
							// 保存用户信息
							uni.setStorageSync('userInfo', {
								product_id: this.product_id,
								device_name: this.device_name,
								authorization: this.authorization,
								device_status: this.device_status,
							});
							uni.showToast({
								title: '数据刷新成功',
								icon: 'success',
								duration: 1000
							});
						} else {
							console.error('请求失败:', res);
						}
					},
					fail: (err) => {
						console.error('请求失败:', err);
					}
				});
			},

			setModelValue(item) {
				const params = {};
				const convertedValue = this.convertValue(item.newValue, item.dataType);

				if (convertedValue !== null) {
					params[item.identifier] = convertedValue;

					uni.request({
						url: 'https://iot-api.heclouds.com/thingmodel/set-device-property',
						method: 'POST',
						header: {
							'Accept': 'application/json, text/plain, */*',
							'authorization': this.authorization,
							'Content-Type': 'application/json'
						},
						data: {
							product_id: this.product_id,
							device_name: this.device_name,
							params: params
						},
						success: (res) => {
							if (res.statusCode === 200) {
								console.log('设置成功:', res);
								uni.showToast({
									title: '设置成功',
									icon: 'success',
									duration: 1000
								});
							} else {
								console.error('设置失败:', res);
								uni.showToast({
									title: '设置失败',
									icon: 'none',
									duration: 1000
								});
							}
						},
						fail: (err) => {
							console.error('设置请求失败:', err);
							uni.showToast({
								title: '设置请求失败',
								icon: 'none',
								duration: 1000
							});
						}
					});
				} else {
					uni.showToast({
						title: '无效的输入',
						icon: 'none',
						duration: 1000
					});
				}
			},

			convertValue(value, type) {
				switch (type) {
					case 'bool':
						return value === 'true' || value === true ? true : value === 'false' || value === false ? false :
							null;
					case 'int32':
					case 'int64':
						return Number.isInteger(Number(value)) ? Number(value) : null;
					case 'float':
					case 'double':
						return !isNaN(Number(value)) ? Number(value) : null;
					case 'string':
						return value;
					default:
						return null;
				}
			}
		}
	};
</script>

<style>
	.container {
		padding: 20px;
		text-align: left;
	}

	.device-info text {
		display: block;
		margin-bottom: 10px;
		font-size: 16px;
	}

	.table-container {
		margin-top: 20px;
	}

	.table-title {
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 10px;
		text-align: center;
	}

	.data-table {
		width: 100%;
		border-collapse: collapse;
		margin-bottom: 20px;
		background-color: #fff;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		border-radius: 4px;
		overflow: hidden;
	}

	.data-table th,
	.data-table td {
		border: 1px solid #ccc;
		padding: 12px;
		text-align: left;
		font-size: 14px;
	}

	.data-table th {
		background-color: #f4f4f4;
		font-weight: bold;
	}

	input {
		width: 100%;
		padding: 2%;
		box-sizing: border-box;
		border: 1px solid #ccc;
		border-radius: 4px;
	}

	button {
		width: 100%;
		padding: 10px;
		background-color: #007aff;
		color: white;
		border: none;
		border-radius: 4px;
		cursor: pointer;
		font-size: 14px;
	}

	button:hover {
		background-color: #005bb5;
	}
</style>